package com.dzu.medium;

import java.util.ArrayList;
import java.util.List;

/**
 * @author ZhaoDong
 * @date 2022/11/1 9:49
 * @description 6. Z 字形变换
 */
public class Test6 {
    public static void main(String[] args) {
        System.out.println(convert("PAYPALISHIRING", 4));


    }

    //  https://leetcode.cn/problems/zigzag-conversion/solution/zzi-xing-bian-huan-by-jyd/
    public static String convert2(String s, int numRows) {
        if (numRows < 2) {
            return s;
        }
        List<StringBuilder> rows = new ArrayList<>();

        for (int i = 0; i < numRows; i++) {
            rows.add(new StringBuilder());
        }
        int i = 0, flag = -1;

        for (char c : s.toCharArray()) {
            rows.get(i).append(c);
            if (i == 0 || i == numRows - 1) {
                flag = -flag;
            }
            i += flag;
        }
        StringBuilder res = new StringBuilder();
        for (StringBuilder row : rows) {
            res.append(row);
        }
        return res.toString();
    }


    public static String convert(String s, int numRows) {

        if (numRows < 2) {
            return s;
        }

        int length = s.length();
        Character[][] arr = new Character[numRows][s.length()];

        int i = 0;
        int j = 0;
        int count = 0;
        for (int k = 0; k < length; k++) {
            if (count < numRows) {
                arr[count][j] = s.charAt(k);
                count++;
                i = count - 1;
                continue;
            }

            i--;
            j++;
            arr[i][j] = s.charAt(k);
            if (i == 0) {
                count = 1;
                j++;
                continue;

            }

            if (i == 1) {
                i--;
                j++;
                count = 0;
            }

        }

        StringBuffer sb = new StringBuffer();


        for (Character[] characters : arr) {
            for (Character character : characters) {
                if (character != null) {
                    sb.append(character);

                }
            }
        }

        return sb.toString();
    }

}

